import { getPermissionRoutes, getLoginUserInfo } from "@/apis/user";

const state = {
  permitIds: [],
  userInfo: {},
  isAdmin: false,
  isInitial: false
};

const mutations = {
  SET_PERMITIDS: (state, permitIds) => {
    state.permitIds = permitIds;
  },
  SET_USERINFO: (state, userInfo) => {
    sessionStorage.setItem("userInfo", JSON.stringify(userInfo));
    state.userInfo = userInfo;
  },
  SET_ISADMIN: (state, isAdmin) => {
    state.isAdmin = isAdmin;
  },
  SET_ISINITIAL: (state, isInitial) => {
    state.isInitial = isInitial;
  }
};

const actions = {
  getPermitIds({ commit }) {
    return new Promise((resolve, reject) => {
      const params = {
        appId: "1",
        userId: sessionStorage.getItem("userId")
      };

      getPermissionRoutes(params)
        .then(res => {
          const permitIds = res.object;

          commit("SET_PERMITIDS", permitIds);
          resolve(permitIds);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  getLoginUserInfo({ commit }, internalUserId) {
    return new Promise(async resolve => {
      const { object } = await getLoginUserInfo({
        internalUserId
      });

      commit("SET_USERINFO", object);
      commit("SET_ISADMIN", object.isAdmin);
      commit("SET_ISINITIAL", object.isInitial);
      resolve(object);
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
